package com.lb.activity.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lb.activity.mapper.RoleMapper;
import com.lb.activity.mapper.UserRoleMapper;
import com.lb.activity.po.Permission;
import com.lb.activity.po.Role;
import com.lb.activity.po.User;
import com.lb.activity.po.UserRole;
import com.lb.activity.service.RoleService;
import com.lb.activity.util.BuildTree;
import com.lb.activity.util.PermissionTree;
import com.lb.activity.util.ResultUtil;
import com.lb.activity.util.SnowflakeIdWorker;
import com.lb.activity.util.emumdata.DataEnum;
import com.lb.activity.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liubin
 */
@Service
public class RoleServiceImpl implements RoleService {


    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private SnowflakeIdWorker idWorker;

    @Override
    public ResultUtil list(RoleVo roleVo) {
        PageHelper.startPage(roleVo.getPage(),roleVo.getLimit());
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("status",DataEnum.DELETE_STATUS.getStatus());
        List<Role> roles = roleMapper.selectByExample(example);
        PageInfo<Role> pageInfo = new PageInfo<>(roles);
        return ResultUtil.build(0, "", Integer.parseInt(String.valueOf(pageInfo.getTotal())), pageInfo.getList());
    }

    @Override
    public ResultUtil add(Role role) {
        role.setId(idWorker.nextId());
        role.setStatus((int) DataEnum.INSERT_STATUS.getStatus());
        // 执行插入
        roleMapper.insertSelective(role);
        return ResultUtil.ok();
    }

    @Override
    public ResultUtil update(Role role) {
        roleMapper.updateByPrimaryKeySelective(role);
        return ResultUtil.ok();
    }

    @Override
    public ResultUtil delete(Long id) {
        Role role = Role.builder().id(id).status((int)DataEnum.DELETE_STATUS.getStatus()).build();
        roleMapper.updateByPrimaryKeySelective(role);
        return ResultUtil.ok();
    }

    @Override
    public Role getOne(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public ResultUtil changeStatus(Long id, boolean boolStatus) {
        Long status = DataEnum.INSERT_STATUS.getStatus();
        // 如果为true ,为 lock 即 禁用
        if(boolStatus){
            status = DataEnum.FORBIDDEN_STATUS.getStatus();
        }
        Role role = Role.builder().id(id).status(Integer.parseInt(status+"")).build();
        roleMapper.updateByPrimaryKeySelective(role);
        return ResultUtil.ok();
    }

    @Override
    public PermissionTree<Role> getRoleTree(Long userId) {
        // 查询所有的role
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andNotEqualTo("status",DataEnum.DELETE_STATUS.getStatus());
        List<Role> allRoles = roleMapper.selectByExample(example);
        // 查询用户的角色
        List<Long> userRoles = roleMapper.selectRoleByUserId(userId);

        List<PermissionTree<Role>> trees = new ArrayList<>();
        //List<StoreAdminPermission> StoreAdminPermissions = getMeunsList();
        for (Role role : allRoles) {
            PermissionTree<Role> tree = new PermissionTree<>();
            tree.setId(role.getId().toString());
            tree.setParentId("0");
            tree.setText(role.getRolename());
            Map<String, Object> state = new HashMap<>(1);
            Long roleId = role.getId();
            if (userRoles!=null&&userRoles.size()>0&&userRoles.contains(roleId)) {
                state.put("selected", true);
            } else {
                state.put("selected", false);
            }
            tree.setState(state);
            trees.add(tree);
        }
        // 默认顶级菜单为０，根据数据库实际情况调整
        PermissionTree<Role> t = BuildTree.build(trees);
        return t;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void modifyUserRoles(Long id, String[] roleIds) {
        // 删除用户所有 角色
        userRoleMapper.removeRoleByUserId(id);
        List<UserRole> userRoles = new ArrayList<>();
        //封装插入的对象
        for (String roleId : roleIds) {
            if(!roleId.equals("-1")){
                UserRole userRole = UserRole.builder()
                        .id(idWorker.nextId())
                        .roleid(Long.valueOf(roleId))
                        .status(Integer.parseInt(DataEnum.INSERT_STATUS.getStatus()+""))
                        .userid(id)
                        .build();
                userRoles.add(userRole);
            }
        }
        if(userRoles.size() > 0){
            //执行批量插入操作
            userRoleMapper.batchSave(userRoles);
        }

    }
}
